package org.cagui.gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;

import org.cagui.core.CertificateManager;
import org.cagui.core.KeyStoreManager;
import org.cagui.listener.KeyStoreRadioButtonListener;

public class Certificates extends JFrame implements ActionListener{
	
	CertificateManager certManager;
	KeyStoreRadioButtonListener certRadioButtonListener;
	
	JFrame frame;

	public Certificates(CertificateManager certManager){
		
		this.certManager = certManager;
		frame = this;
		
		setSize(700,500);
        setTitle("Certificates");
        
        // Top button panel
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
        buttonPanel.setBorder(new EmptyBorder(10, 10, 10, 10) );
        
        // Adding buttons
    	JButton importKeyStore;
    	JButton deleteKeyStore;
    	JButton openKeyStore;
    	
        openKeyStore = new JButton("Open selected certificate");
        openKeyStore.setActionCommand("opencert");
        openKeyStore.addActionListener(this);

        importKeyStore = new JButton("Import certificate");
        importKeyStore.setActionCommand("importcert");
        importKeyStore.addActionListener(this);

        deleteKeyStore = new JButton("Delete certificate");
        deleteKeyStore.setActionCommand("deletecert");
        deleteKeyStore.addActionListener(this);

        buttonPanel.add(openKeyStore);
        buttonPanel.add(Box.createRigidArea(new Dimension(10, 10)));
        buttonPanel.add(importKeyStore);
        buttonPanel.add(Box.createRigidArea(new Dimension(10, 10)));
        buttonPanel.add(deleteKeyStore);
        
        certRadioButtonListener = new KeyStoreRadioButtonListener();
        
        // LISTNING CERTS

        ButtonGroup group = new ButtonGroup();
        JPanel radioButtonPanel = new JPanel();
        radioButtonPanel.setLayout(new BoxLayout(radioButtonPanel, BoxLayout.Y_AXIS));
        radioButtonPanel.setBorder(new EmptyBorder(20, 80, 20, 80) );
        
        radioButtonPanel.add(new JLabel("Avaliable certificates:"));
        
        File dir = new File("./certificates/");

		String[] children = dir.list();
		if (children == null) {
		} 
		else {
			
			for (int i = 0; i < children.length; i++) {

				String filename = children[i];

		        JRadioButton keyStoreButton;
		        
				keyStoreButton = new JRadioButton(i+1 + ". " + filename);
				
		        keyStoreButton.setMnemonic(KeyEvent.VK_B);
		        keyStoreButton.setActionCommand(filename);
		        keyStoreButton.addActionListener(certRadioButtonListener);
		        group.add(keyStoreButton);
		        radioButtonPanel.add(keyStoreButton);
				
			}

			if (children.length == 0) radioButtonPanel.add(new JLabel(" > No certificates avaliable"));
						
		}    
        
        
        JPanel framePanel = new JPanel();
        framePanel.setLayout(new BoxLayout(framePanel, BoxLayout.Y_AXIS));
        framePanel.add(buttonPanel);
        
        Box radioButtonBox = Box.createHorizontalBox();
        radioButtonBox.add(radioButtonPanel);
        radioButtonBox.add(Box.createHorizontalGlue());
        framePanel.add(radioButtonBox);
        this.setContentPane(framePanel);	

        this.setVisible(true);
		
				
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		Object actionCommand = event.getActionCommand();
		
		String keyName = certRadioButtonListener.getSelected();
		
		if (actionCommand.equals("opencert")) {
			if (!keyName.equals("none")){
				
				new CertificateData(certManager.readCertificateFromFile(keyName));
				
			}
			else {
				JOptionPane.showMessageDialog(frame,
					    "You have to select certificate to open!",
					    "Empty selection",
					    JOptionPane.WARNING_MESSAGE);
			}
			
		}
		else if (actionCommand.equals("importcert")) {
			String filename = "..";
			JFileChooser fc = new JFileChooser(new File(filename));

			fc.showOpenDialog(frame);
			
			if (fc.getSelectedFile() != null){
				File selectedFile = fc.getSelectedFile();
				
				File newFile = new File(CertificateManager.defaultCertificatesPath + selectedFile.getName());
				
				InputStream in;
				OutputStream out;
				try {
					in = new FileInputStream(selectedFile);
					out = new FileOutputStream(newFile); 
					
					byte[] buf = new byte[1024];
					int len;
					while ((len = in.read(buf)) > 0) {
						out.write(buf, 0, len);
					}
					in.close();
					out.close();
					
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}			
				
				redraw();
			}
		}
		else if (actionCommand.equals("deletecert")) {
			if (!keyName.equals("none")){
				int n = JOptionPane.showConfirmDialog(
					    frame,
					    "Are you sure?",
					    "Delete keystore?",
					    JOptionPane.YES_NO_OPTION);
				
				if (n == JOptionPane.YES_OPTION){
					File file = new File(CertificateManager.defaultCertificatesPath + keyName);
					
					file.delete();
					
					redraw();				
				}
			}
			else {
				JOptionPane.showMessageDialog(frame,
					    "You have to select certificate to delete!",
					    "Empty selection",
					    JOptionPane.WARNING_MESSAGE);
			}
		}
	}

	public void redraw() {
		frame.dispose();
		new Certificates(certManager);
	}
}
